/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2023-11-09 16:34:03
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2023-11-14 17:13:51
 * @FilePath: /three-react/src/pages/CurveGeometry/Line1.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect, useRef } from "react"
import createRender from '@/createRender';
import * as THREE from 'three'
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";



const state = {}
export default function Page() {

  const container = useRef(null);
  useEffect(() => {
    if (!state.isMounted) {
      createRender(container)(render);
      state.isMounted = true;
    }
  }, [])



  function render(scene) {
    const loader = new GLTFLoader();
    loader.load('../terrain.glb', function(model) {

    

      const mash = model.scene.children[0]

      const position = mash.geometry.attributes.position;
      const count = position.count;

      const heights = []
      for (let index = 0; index < count; index++) {
        heights.push(position.getY(index))
      }

      heights.sort((a,b) => a- b)
      const min = heights[0]
      const max = heights[heights.length-1]
      const height = max - min;
 

      const c1 = new THREE.Color(0x0000ff);//山谷颜色
      const c2 = new THREE.Color(0xff0000);//山顶颜色
      const colors = []

      for (let index = 0; index < count; index++) {
        const precent = (position.getY(index) - min ) / height;
        const color = c1.clone().lerp(c2, precent)
        colors.push(color.r, color.g, color.b)
      }
      mash.geometry.attributes.color = new THREE.BufferAttribute(new Float32Array(colors), 3)
      mash.material.vertexColors = true
      scene.add(model.scene)

    })

    


  }

  return (
    <div id="container" className="full container" ref={container}></div>
  )
}